package com.ship.auth.controller;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.auth.entity.vo.AuthenticationUserVo;
import com.ship.auth.service.AuthenticationService;
import com.ship.auth.service.LoginRecordService;
import com.ship.common.core.base.LoginRecord;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.redis.configure.RedisRepository;
import com.ship.common.security.auth.AuthUtil;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Date;
import java.util.Random;


@RequestMapping("workbench")
@RestController
@CrossOrigin
public class AuthenticationController {
    @Autowired
    private AuthenticationService authenticationService;

//    @Autowired
//    private UserService userService;

    @Autowired
    private RedisRepository redisRepository;
    @Autowired
    private LoginRecordService loginRecordService;

    @Value("${loginUrl}")
    private String loginUrl;

    /**
     * 认证接口--弹出登录页面
     *
     * @param type
     * @return
     */
    @GetMapping("/getAuthorize/{type}")
    @ResponseBody
    public String authenticationLogin(@PathVariable String type) {
        String htmlContent = authenticationService.authenticationLogin(type);
        return htmlContent;
    }

    /**
     * 通过授权码接口返回地址，获取token
     *
     * @param request
     */
    @GetMapping("/test")
    public void getTestToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String code = request.getParameter("code").toString();
//        code = code.replace("[", "");
//        code = code.replace("]", "");
//        String state = request.getParameter("state").toString();
//        AuthenticationUserVo authenticationUserVo = authenticationService.getAuthenticationToken(code, state);
//
//        //登录日志
//        LoginRecord loginRecord = new LoginRecord();
//        String uaStr = request.getHeaders("User-Agent").toString();
//        UserAgent ua = UserAgentUtil.parse(uaStr);
//        loginRecord.setOs(ua.getOs().toString());
//        loginRecord.setDevice(ua.getOs().toString());
//        loginRecord.setBrowser(ua.getBrowser().toString());
//        String ip = "";
//        if (null != request.getHeader("x-forwarded-for")) {
//            ip = request.getHeaders("x-forwarded-for").toString();
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            if (null != request.getHeaders("Proxy-Client-IP")) {
//                ip = request.getHeaders("Proxy-Client-IP").toString();
//            }
//        }
//
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            if (null != request.getHeaders("X-Forwarded-For")) {
//                ip = request.getHeaders("X-Forwarded-For").toString();
//            }
//        }
//
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            if (null != request.getHeaders("WL-Proxy-Client-IP")) {
//                ip = request.getHeaders("WL-Proxy-Client-IP").toString();
//            }
//        }
//
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            if (null != request.getHeaders("X-Real-IP")) {
//                ip = request.getHeaders("X-Real-IP").toString();
//            }
//        }
//
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            if (null != request.getRemoteAddr()) {
//                ip = request.getRemoteAddr();
//            }
//        }
//
//        if ("/0:0:0:0:0:0:0:1".equals(ip)) {
//            ip = "127.0.0.1";
//        }
//
//        if (ip.contains(",")) {
//            ip = ip.split(",")[0];
//        }
//        loginRecord.setIp(ip);
//        loginRecord.setCreateTime(new Date());
//        loginRecord.setCreateDate(loginRecord.getCreateTime());
//        if (StringUtils.isNotBlank(authenticationUserVo.getErrcode()) && !authenticationUserVo.getErrcode().equals("0")) {
//            loginRecord.setLoginType(2);
//        } else {
//            loginRecord.setLoginType(1);
//        }
//        loginRecordService.save(loginRecord);
//
//        if(authenticationUserVo.getJudge()){
//            int randomState = new Random().nextInt(999901) + 100;
//            String state1 = String.valueOf(randomState);
//            String url = "https://devau.cnooc.com.cn/idp/oauth2/authorize?state=" + state1 + "&response_type=code&client_id=lngyscbdd&redirect_uri=https://10.75.34.224/api/workbench/test1";
//            System.out.println("url:"+url);
//            response.sendRedirect(url);
//        }
//        response.sendRedirect(url);
    }

    @GetMapping("/test1")
    public void getTestToken1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code").toString();
        code = code.replace("[", "");
        code = code.replace("]", "");
        String state = request.getParameter("state").toString();
        String out = request.getParameter("out");
        AuthenticationUserVo authenticationUserVo = authenticationService.getAuthenticationToken(code, state);

        //登录日志
        LoginRecord loginRecord = new LoginRecord();
        String uaStr = request.getHeaders("User-Agent").toString();
        UserAgent ua = UserAgentUtil.parse(uaStr);
        loginRecord.setOs(ua.getOs().toString());
        loginRecord.setDevice(ua.getOs().toString());
        loginRecord.setBrowser(ua.getBrowser().toString());
        String ip = "";
        if (null != request.getHeader("x-forwarded-for")) {
            ip = request.getHeaders("x-forwarded-for").toString();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("Proxy-Client-IP")) {
                ip = request.getHeaders("Proxy-Client-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("X-Forwarded-For")) {
                ip = request.getHeaders("X-Forwarded-For").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("WL-Proxy-Client-IP")) {
                ip = request.getHeaders("WL-Proxy-Client-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("X-Real-IP")) {
                ip = request.getHeaders("X-Real-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getRemoteAddr()) {
                ip = request.getRemoteAddr();
            }
        }

        if ("/0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }

        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        loginRecord.setIp(ip);
        loginRecord.setCreateTime(new Date());
        loginRecord.setCreateDate(loginRecord.getCreateTime());
        if (StringUtils.isNotBlank(authenticationUserVo.getErrcode()) && !authenticationUserVo.getErrcode().equals("0")) {
            loginRecord.setLoginType(2);
        } else {
            loginRecord.setLoginType(1);
        }
        loginRecordService.save(loginRecord);

    }

    /**
     * 通过授权码接口返回地址，获取token
     *
     * @param request
     */
    @GetMapping("")
    public void getToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AuthenticationUserVo authenticationUserVo = new AuthenticationUserVo();
                String code = request.getParameter("code").toString();
        code = code.replace("[", "");
        code = code.replace("]", "");
        String state = request.getParameter("state").toString();
        authenticationUserVo = authenticationService.getAuthenticationToken(code, state);

        //登录日志
        LoginRecord loginRecord = new LoginRecord();
        String uaStr = request.getHeaders("User-Agent").toString();
        UserAgent ua = UserAgentUtil.parse(uaStr);
        loginRecord.setOs(ua.getOs().toString());
        loginRecord.setDevice(ua.getOs().toString());
        loginRecord.setBrowser(ua.getBrowser().toString());
        String ip = "";
        if (null != request.getHeader("x-forwarded-for")) {
            ip = request.getHeaders("x-forwarded-for").toString();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("Proxy-Client-IP")) {
                ip = request.getHeaders("Proxy-Client-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("X-Forwarded-For")) {
                ip = request.getHeaders("X-Forwarded-For").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("WL-Proxy-Client-IP")) {
                ip = request.getHeaders("WL-Proxy-Client-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getHeaders("X-Real-IP")) {
                ip = request.getHeaders("X-Real-IP").toString();
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (null != request.getRemoteAddr()) {
                ip = request.getRemoteAddr();
            }
        }

        if ("/0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }

        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        loginRecord.setIp(ip);
        loginRecord.setCreateTime(new Date());
        loginRecord.setCreateDate(loginRecord.getCreateTime());
        if (StringUtils.isNotBlank(authenticationUserVo.getErrcode()) && !authenticationUserVo.getErrcode().equals("0")) {
            loginRecord.setLoginType(2);
        } else {
            loginRecord.setLoginType(1);
        }
        loginRecordService.save(loginRecord);
//        String url = "https://10.75.34.224/resourcecontract?token="+authenticationUserVo.getToken()+"&username="+authenticationUserVo.getUsername();
//        String url = "https://10.75.33.149/resourcecontract?token="+authenticationUserVo.getToken()+"&username="+authenticationUserVo.getUsername();
        String url = "https://lngshipping.cgp.cnooc/resourcecontract?token="+authenticationUserVo.getToken()+"&username="+authenticationUserVo.getUsername();//生产
//        String url = "https://lngshippingcs.cgp.cnooc/resourcecontract?token="+authenticationUserVo.getToken()+"&username="+authenticationUserVo.getUsername();//测试
        response.sendRedirect(url);
    }

    @GetMapping("/getTestUrl")
    @ResponseBody
    public JsonResult getTestUrl(HttpServletRequest request) {

        int randomState = new Random().nextInt(999901) + 100;
        String state = String.valueOf(randomState);
        String url = loginUrl+state;
        System.out.println("getTestUrl的url："+ url);
        return JsonResult.success(url);
    }

//    @GetMapping("/getTestUrl")
//    @ResponseBody
//    public String getProductionUrl() {
//        int randomState = new Random().nextInt(999901) + 100;
//        String state = String.valueOf(randomState);
//        String url = "https://au.cnooc.com.cn/idp/oauth2/authorize?state="+state+"&response_type=code&client_id=lngyscbdd&redirect_uri=https://10.75.33.149/api/workbench";
//        return url;
//    }
//    @GetMapping("/test")
//    @ResponseBody
//    public String test() {
//        String expiresIn = "3600";
//        String username = "ex_dingyi3";
//        String accessToken = "86b171c772d490c5d39c652588ba5ca4";
//        System.out.println("username:" + username);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//
//        queryWrapper.eq("username", username);
//////        System.out.println(MD5.encrypt(member.getPassword()));
////        queryWrapper.eq("password", MD5.encrypt(member.getPassword()));
//
//        User user = userService.getOne(queryWrapper, false);
//        String json = JSONObject.toJSONString(user);
//        redisRepository.setExpire("IOTDM:USER:SESSION_" + accessToken, json, Long.parseLong(expiresIn));
////        System.out.println("加密报文2:" + target2);
//        return "succeed";
//    }

//    @GetMapping("/test")
//    @ResponseBody
//    public Mono<Void> test(ServerWebExchange serverWebExchange) {
//        String expiresIn = "3600";
//        QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", "ex_dingyi3");
//////        System.out.println(MD5.encrypt(member.getPassword()));
//////        queryWrapper.eq("password", MD5.encrypt(member.getPassword()));
//        LoginUser user = userService.getOne(queryWrapper, false);
//        String json = JSONObject.toJSONString(user);
//
//        redisRepository.setExpire("IOTDM:USER:SESSION_9961a9a3-0636-4b4a-ba9f-b58658ef3e18", json, Long.parseLong(expiresIn));
//
//        String url = "https://10.75.34.224/Login?token=f5a0a55a12313db25ffed235167f63ad";
////        String url = "http://106.12.241.246:18089/resourcecontract&token=9961a9a3-0636-4b4a-ba9f-b58658ef3e18";
////        String token = "IOTDM:USER:SESSION_9961a9a3-0636-4b4a-ba9f-b58658ef3e18";
////        serverWebExchange.getResponse().getHeaders().add("authentication",token);
////        serverWebExchange.getResponse().getHeaders().add("authentication",token);
////        serverWebExchange.getRequest().mutate().header("authentication",token).build();
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.SEE_OTHER);
//        serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url));
//        return serverWebExchange.getResponse().setComplete();
//    }
//
//    @GetMapping("/test2")
//    @ResponseBody
//    public Mono<Void> test2(ServerWebExchange serverWebExchange) throws UnsupportedEncodingException {
//        String expiresIn = "3600";
//        QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", "ex_dingyi3");
//////        System.out.println(MD5.encrypt(member.getPassword()));
//////        queryWrapper.eq("password", MD5.encrypt(member.getPassword()));
//        LoginUser user = userService.getOne(queryWrapper, false);
//        String json = JSONObject.toJSONString(user);
//
//        redisRepository.setExpire("IOTDM:USER:SESSION_9961a9a3-0636-4b4a-ba9f-b58658ef3e18", json, Long.parseLong(expiresIn));
//
//        String url = "https://10.75.34.224/Login"+"\\&" +"token=f5a0a55a12313db25ffed235167f63ad";
////        String url = URLEncoder.encode(urld,"UTF-8");
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.SEE_OTHER);
//        serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url));
//        return serverWebExchange.getResponse().setComplete();
//    }
//
//    @GetMapping("/test3")
//    @ResponseBody
//    public Mono<Void> test3(ServerWebExchange serverWebExchange) throws UnsupportedEncodingException {
//        String expiresIn = "3600";
//        QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", "ex_dingyi3");
//////        System.out.println(MD5.encrypt(member.getPassword()));
//////        queryWrapper.eq("password", MD5.encrypt(member.getPassword()));
//        LoginUser user = userService.getOne(queryWrapper, false);
//        String json = JSONObject.toJSONString(user);
//
//        redisRepository.setExpire("IOTDM:USER:SESSION_9961a9a3-0636-4b4a-ba9f-b58658ef3e18", json, Long.parseLong(expiresIn));
//
//        String url = "https://10.75.34.224/resourcecontract?token=9961a9a3-0636-4b4a-ba9f-b58658ef3e18&username=ex_dingyi3";
////        String url = URLEncoder.encode(urld,"UTF-8");
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.SEE_OTHER);
//        serverWebExchange.getResponse().getHeaders().setLocation(URI.create(url));
//        return serverWebExchange.getResponse().setComplete();
//    }
}
